/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-09-09     WCH        the first version
 */

#include "board.h"
#include <stdint.h>
#include "drv_usart.h"
#include <rthw.h>
#include <rtthread.h>

extern uint32_t SystemCoreClock;

static uint32_t _SysTick_Config(rt_uint32_t ticks)
{
    NVIC_SetPriority(SysTicK_IRQn,0xf0);
    NVIC_SetPriority(Software_IRQn,0xf0);
    NVIC_EnableIRQ(SysTicK_IRQn);
    NVIC_EnableIRQ(Software_IRQn);
    SysTick->CTLR=0;
    SysTick->SR=0;
    SysTick->CNT=0;
    SysTick->CMP=ticks-1;
    SysTick->CTLR=0xF;
    return 0;
}

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
//#define RT_HEAP_SIZE (1024 * 6)
//static uint32_t rt_heap[RT_HEAP_SIZE];
//RT_WEAK void *rt_heap_begin_get(void)
//{
//    return rt_heap;
//}
//
//RT_WEAK void *rt_heap_end_get(void)
//{
//    return rt_heap + RT_HEAP_SIZE;
//}
#endif

/**
 * This function will initial your board.
 */
void rt_hw_board_init()
{
    /* System Tick Configuration */
    _SysTick_Config(SystemCoreClock / RT_TICK_PER_SECOND);

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
    rt_system_heap_init((void *)HEAP_BEGIN, (void *)HEAP_END);

#endif
    /* USART driver initialization is open by default */
#ifdef RT_USING_SERIAL
    rt_hw_usart_init();
#endif
#ifdef RT_USING_CONSOLE
    rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif
    /* Call components board initial (use INIT_BOARD_EXPORT()) */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif

}


void SysTick_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
void SysTick_Handler(void)
{
    GET_INT_SP();
    /* enter interrupt */
    rt_interrupt_enter();
    SysTick->SR=0;
    rt_tick_increase();
    /* leave interrupt */
    rt_interrupt_leave();
    FREE_INT_SP();

}

void rt_hw_us_delay(rt_uint32_t us)
{
    uint64_t total_delay_ticks, us_ticks, start, now, delta, reload;

    start = SysTick->CNT;
    reload = SysTick->CMP;
    us_ticks = SystemCoreClock / 8000000UL;
    total_delay_ticks = (uint32_t)us * us_ticks;
    RT_ASSERT(total_delay_ticks < reload);

    do{
        now = SysTick->CNT;
        delta = start > now ? start - now : reload + start - now;
    }while(delta < total_delay_ticks);
    // 这里start > now ? 是通过利用SysTick计数器的递减计数来判定，是否发生了一次定时器溢出
    //举STM32例说明一下：
    //例子1： start = 70000；total_delay_ticks = 50000（约694.4us）；
    //那么，当now = SysTick->VAL= 19999，即可满足条件,delta = start > now ? start - now
    //例子2： start = 70000；total_delay_ticks = 80000（约1111.1us）；
    //那么，无论计数器怎么计数，都不能满足条件；当刚溢出时，start < now =reload + start - now 总数<reload 1ms; 当溢出超过1ms时，又会出现start > now =start - now 总数计算明显出现了错位;
    //所以，为了保险起见，这个usdelay的调用最好不要超过一次中断的周期时长，即total_delay_ticks<(reload = SysTick->LOAD)
}
